<?php


namespace app\controller\v1;

use app\BaseController;
use app\service\PayService;
use app\service\WechatPaymentService;
use think\facade\Log;
use think\Request;

class PayController extends BaseController
{
    // 微信支付回调
    public function wechatNotify(Request $request)
    {
        $params = $request->getContent();//$this->request->all();
        // 接收微信支付成功回调内容
        $inWechatpaySignature = $this->getRequestHeader('Wechatpay-Signature');
        $inWechatpayTimestamp = $this->getRequestHeader('Wechatpay-Timestamp');
        $inWechatpaySerial    = $this->getRequestHeader('Wechatpay-Serial');
        $inWechatpayNonce     = $this->getRequestHeader('Wechatpay-Nonce');
        Log::info('微信支付回调参数：' . json_encode($params));
        Log::info('微信支付回调参数：' . json_encode([
            'Wechatpay-Signature' => $inWechatpaySignature,
            'Wechatpay-Timestamp' => $inWechatpayTimestamp,
            'Wechatpay-Serial' => $inWechatpaySerial,
            'Wechatpay-Nonce' => $inWechatpayNonce,
        ]));
        $params = is_array($params)?$params:json_decode($params,true);
        // 验证数据
        $validate = validate([
            'create_time' => 'require',
            'resource_type' => 'require',
            'event_type' => 'require',
            'summary' => 'require',
            'resource' => 'require',
        ])->message([
            'create_time.require' => '创建时间不能为空',
            'resource_type.require' => '资源类型不能为空',
            'event_type.require' => '事件类型不能为空',
            'summary.require' => '摘要不能为空',
            'resource.require' => '资源不能为空',
        ]);
        if (!$validate->check($params)) {
            return json([
                'code' => 204,
                'message' => $validate->getError(),
            ]);
        }
        try {
            // 解密回调
            $wechatPaymentService = new WechatPaymentService();
            $result = $wechatPaymentService->decryptNotify($params['resource'], $inWechatpaySignature, $inWechatpayTimestamp, $inWechatpaySerial, $inWechatpayNonce);
            Log::info('微信支付回调解密结果：' . json_encode($result));
            if (empty($result)) {
                throw new \Exception('微信支付回调解密失败');
            }
              $payService = new PayService();
            if ($result['trade_state']=='SUCCESS'){
                // 成功操作
                $payService->paySuccess($result);
            }else{
                // 失败操作
                $payService->payFail($result);
            }
        } catch (\Exception $e) {
            // Log::info('微信支付回调异常：'.$e->getMessage());
            trace('error', '微信支付回调异常：' . $e->getTraceAsString());
            return json([
                'code' => 204,
                'message' => $e->getMessage(),
            ]);
        }
        // if($result){
        //     return $this->success('支付成功');
        // }
        return json([
            'code' => 200,
            'message' => '',
        ]);

        // $wechatPaymentService = new WechatPaymentService();
        // $result = $wechatPaymentService->notify($params);
        // if($result){
        //     return $this->success('支付成功');
        // }
    }

    protected function getRequestHeader($name)
    {
        // 在许多 PHP 环境，HTTP 请求头会放在 $_SERVER 中，前缀为 HTTP_
        $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
        if (isset($_SERVER[$key])) return $_SERVER[$key];

        // 一些服务器把原样头放到 apache_request_headers() 中
        if (function_exists('apache_request_headers')) {
            $headers = apache_request_headers();
            foreach ($headers as $k => $v) {
                if (strtolower($k) === strtolower($name)) return $v;
            }
        }
        return null;
    }
}
